class Admin::TopicsController < AdminController
  def index
    @topics = Topic.all
    if params[:state].presence
      @topics = @topics.where(state: params[:state])
    end
    if params[:sale_or_buy].presence
      @topics = @topics.where(sale_or_buy: params[:sale_or_buy])
    end
    @topics = @topics.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def new
    @topic = Topic.new
  end

  def create
    @topic = Topic.new topic_params
    if @topic.save
      redirect_to admin_topics_path, notice: "保存成功！"
    else
      redirect_to admin_topics_path, notice: "保存失败！"
    end
  end

  def edit
    @topic = Topic.find params[:id]
  end

  def update
    @topic = Topic.find params[:id]
    if @topic.update topic_params
      redirect_to admin_topics_path, notice: "更新成功！"
    else
      redirect_to admin_topics_path, notice: "更新失败！"
    end
  end
  
  def destroy
    @topic = Topic.find params[:id]
    if @topic.destroy
      redirect_to admin_topics_path, notice: "删除成功."
    else
      redirect_to admin_topics_path, notice: "删除失败."
    end
  end

  private

  def topic_params
    params.require(:topic).permit(:name, :title, :price, :phone, :province_id, :city_id, :district_id, :description, :user_id, :state)
  end
end
